package work.xiaohong.gupiao.time;

import work.xiaohong.gupiao.pojo.HttpResult;
import work.xiaohong.gupiao.pojo.Jijin;
import work.xiaohong.gupiao.pojo.JijinFreeNumber;
import work.xiaohong.gupiao.service.JijinFreeNumberService;
import work.xiaohong.gupiao.service.JijinService;
import work.xiaohong.gupiao.util.JijinUrlUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author xiaohong
 * @Description 定时爬取最新内容存入数据库并更新redis
 * @date 2020/12/4 0004 11:01
 */
@Component
public class MySqlTask {

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    public JijinService jijinService;

    @Autowired
    private JijinFreeNumberService jijinFreeNumberService;


    public CloseableHttpClient httpClient;
    public HttpGet httpGet;
    public final String CONTENT_TYPE = "Content-Type";

    /**
     * 每天的15:10执行一次，更新股票数据
     */
//    @Scheduled(cron = "0 10 15 * * ?")
    public void gupiaoTask() throws Exception {

        ArrayList<String> urls = new ArrayList<>();
        urls.add("baijiu");
        urls.add("baoxian");
        urls.add("chuangye");
        urls.add("chuanmei");
        urls.add("hushen");
        urls.add("jijian");
        urls.add("jungong");
        urls.add("meitan");
        urls.add("nongye");
        urls.add("shangzheng");
        urls.add("shenzhen");
        urls.add("tmt");
        urls.add("xiaofei");
        urls.add("xinnengyuan");
        urls.add("yinhang");
        urls.add("yiyao");
        urls.add("zhengquan");

        for (int i = 0; i < urls.size(); i++) {
//            String s = get("http://121.43.153.14:18888/" + urls.get(i));
            String s = get("http://127.0.0.1:18888/" + urls.get(i));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            System.out.println(format.format(new Date()) + "完成" + urls.get(i) + "任务");
            System.out.println(s);
            Thread.sleep(2000);
        }

    }


    /**
     * 每天的23:00执行一次，计算卖出买入数据
     */
    @Scheduled(cron = "0 00 23 * * ?")
    public void JijinTask() throws Exception {

        // 获取所有交易中的数据
        List<Jijin> list = jijinService.findIsDoing();



        // 判断是卖出还是买入
        for (Jijin jj : list) {

            Jijin resultJijin = new Jijin();

            // 获取目前基金净值
            String url = JijinUrlUtil.creatUrl(jj.getCode(), 13);
            HttpResult httpResult = JijinHttpUtil.sendGetReq(url);
            Float nav = httpResult.getGsz();  //获取当前净值

            DecimalFormat df = new DecimalFormat("0.00");

            if (jj.getStatus() == 3){
                // 卖出
                resultJijin.setId(jj.getId());
                resultJijin.setSellPrice(nav+"");
                resultJijin.setSellMoney(
                    df.format(
                    Float.parseFloat(jj.getBuyNumber())*nav
                    )
                );
                resultJijin.setStatus(4);
                resultJijin.setSellDay(new Date());
                resultJijin.setDealDay(new Date());
            }else{
                // 买入
                resultJijin.setBuyPrice(nav+"");
                Float number = Float.parseFloat(jj.getBuyMoney())/nav;
                // 保留两位小数
                resultJijin.setBuyNumber(df.format(number));
                resultJijin.setStatus(1);
//                resultJijin.setFreeDay(8);
                resultJijin.setId(jj.getId());
                resultJijin.setDealDay(new Date());
            }

            // 保存数据库
            jijinService.update(resultJijin);
//            System.out.println(resultJijin);
//            Thread.sleep(5000);
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date()) + "完成计算任务");


    }


    /**
     * 每天的00:01执行一次，更新可赎份额
     */
    @Transactional
    @Scheduled(cron = "0 01 00 * * ?")
    public void freeNumberTask() throws Exception {

        // 遍历所有订单，将可赎天数减少1
        List<Jijin> all = jijinService.findIsNotFree();
        for (Jijin jijin : all) {
            if (jijin.getFreeDay() != null && jijin.getFreeDay() != 0){
                jijin.setFreeDay(jijin.getFreeDay()-1);
                //更新基金
                jijinService.update(jijin);
                if (jijin.getFreeDay() == 0){
                    //更新可赎份额
                    JijinFreeNumber jijinFreeNumber = new JijinFreeNumber();
                    jijinFreeNumber.setCode(jijin.getCode());
                    List<JijinFreeNumber> list = jijinFreeNumberService.findList(jijinFreeNumber);
                    if (list != null && list.size() != 0){
                        jijinFreeNumber = list.get(0);
                        jijinFreeNumber.setFreeNumber((Float.valueOf(jijinFreeNumber.getFreeNumber())+Float.valueOf(jijin.getBuyNumber()))+"");
                        jijinFreeNumberService.update(jijinFreeNumber);
                    }else  {
                        System.out.println("没有该基金的可赎份额记录,现在创建");
                        jijinFreeNumber.setFreeNumber(Float.valueOf(jijin.getBuyNumber())+"");
                        jijinFreeNumber.setName(jijin.getName());
                        jijinFreeNumberService.add(jijinFreeNumber);
                    }

                }
            }
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(format.format(new Date()) + "完成更新可赎份额任务");

    }



    public static String get(String url){
        String result = "";
        HttpGet get = new HttpGet(url);
        try{
            // 设置请求头 伪装代理
            get.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36");
            get.setHeader("Host","api.money.126.net");

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(get);
//            Header[] allHeaders = get.getAllHeaders();
//            System.out.println("发送的请求头：" );
//            for (int i = 0; i < allHeaders.length; i++) {
//                System.out.println(allHeaders[i]);
//            }

            result = getHttpEntityContent(response);

            if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                result = "服务器异常";
            }
        } catch (Exception e){
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally{
            get.abort();
        }
        return result;
    }


    public static String getHttpEntityContent(HttpResponse response) throws UnsupportedOperationException, IOException{
        String result = "";
        HttpEntity entity = response.getEntity();
        if(entity != null){
            InputStream in = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber= new StringBuilder();
            String line = null;
            while((line = br.readLine())!=null){
                strber.append(line+'\n');
            }
            br.close();
            in.close();
            result = strber.toString();
        }

        return result;

    }


    /**
     * 使用POST格式发送form-data格式参数，并获取响应字符串
     * @param path
     * @param params
     * @return
     */
    public String sendSmsFormByPost(String path, Map<String ,Object> params){
        URL u = null;
        HttpURLConnection con = null;
        // 构建请求参数
        StringBuffer sb = new StringBuffer();
        if (params != null) {
            for (Map.Entry<String, Object> e : params.entrySet()) {
                sb.append(e.getKey());
                sb.append("=");
                sb.append(e.getValue());
                sb.append("&");
            }
            //去掉最后一个&
            sb.substring(0, sb.length() - 1);
        }
        // 尝试发送请求
        try {
            u = new URL(path);
            con = (HttpURLConnection) u.openConnection();
//            POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            osw.write(sb.toString());
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }

        // 读取返回内容
        StringBuffer buffer = new StringBuffer();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }



}
